package com.tdam2011.grupo05.ui.activities.message;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.control.app.TdamApplication;
import com.tdam2011.grupo05.entities.contact.ContactWeb;
import com.tdam2011.grupo05.entities.message.MessageWeb;
import com.tdam2011.grupo05.entities.thread.ThreadWeb;
import com.tdam2011.grupo05.services.MessageService;
import com.tdam2011.grupo05.services.ServiceHelper;
import com.tdam2011.grupo05.ui.activities.DashboardActivity;
import com.tdam2011.grupo05.ui.activities.message.AddContactWebFragment.AddContactCallback;
import com.tdam2011.grupo05.ui.activities.message.MessageListFragment.MensajeCallback;
import com.tdam2011.grupo05.ui.activities.message.SelectContactFragment.UsuarioCallback;
import com.tdam2011.grupo05.ui.activities.message.ThreadListFragment.ThreadCallback;

public class MessageWebActivity extends FragmentActivity implements
		ThreadCallback, UsuarioCallback, MensajeCallback, AddContactCallback {

	protected static final String URI_PICKED = "uri_picked";
	private static final String ADD_CONTACT = "add_contact_fragment";
	private static final String TAG = "MessageWebActivity";
	private static final String LIST_THREAD_FRAGMENT = "thread_list";
	private static final String LIST_CONTACT_FRAGMENT = "contact_list";

	private static final int PICK_REQUEST = 1;

	private final ExecutorService mExecutor = Executors.newCachedThreadPool();

	private FragmentManager manager;
	private ThreadListFragment mListThreadFragment;
	private AddContactWebFragment mAddContactWebFragment;

	private ServiceHelper mServiceHelper;

	private final Handler mHandler = new Handler();

	private final ServiceConnection mService = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			((MessageService.MainBinder) service)
					.setActivity(MessageWebActivity.this);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_message_web);

		Log.i(TAG, "onCreate");

		mListThreadFragment = new ThreadListFragment();

		manager = getSupportFragmentManager();

		manager.beginTransaction()
				.add(R.id.fragment_web_conteiner, mListThreadFragment,
						LIST_THREAD_FRAGMENT).commit();

		mServiceHelper = ServiceHelper.getIntance(this);

	}

	@Override
	protected void onStart() {
		Log.i(TAG, "onStart");
		bindService(new Intent(this, MessageService.class), mService,
				BIND_AUTO_CREATE);
		super.onStart();

	}

	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
	}

	@Override
	protected void onPause() {
		Log.i(TAG, "onPause");
		super.onPause();
	}

	@Override
	protected void onStop() {
		Log.i(TAG, "onStop");
		unbindService(mService);
		super.onStop();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_message_web, menu);
		return true;
	}

	public void showDialog(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	@Override
	public void onSelectedUser(final long idContact) {
		Log.d(TAG, "on selected contact: " + idContact);

		Runnable r = new Runnable() {

			@Override
			public void run() {
				ThreadWeb thread = mServiceHelper.getThread(idContact,
						((TdamApplication) getApplication())
								.getCurrentAccount().getId());
				final ThreadWeb t = thread;
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						FragmentTransaction ft = manager.beginTransaction();

						MessageListFragment mensaje = (MessageListFragment) manager
								.findFragmentByTag(t.getUser().getName());
						if (mensaje == null) {
							mensaje = new MessageListFragment();
						}
						mensaje.setThreadWeb(t);
						ft.setCustomAnimations(android.R.anim.slide_in_left,
								android.R.anim.slide_out_right);
						ft.replace(R.id.fragment_web_conteiner, mensaje, t
								.getUser().getName());
						ft.addToBackStack(null);
						ft.commit();
					}
				});

			}
		};
		mExecutor.submit(r);
	}

	@Override
	public void sendMessage(MessageWeb message, ThreadWeb thread) {
		mServiceHelper.sendNewMessage(message, thread);
	}

	@Override
	public void onNewMessage() {
		Log.d(TAG, "on New Message");
		Runnable r = new Runnable() {

			@Override
			public void run() {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						FragmentTransaction t = manager.beginTransaction();

						SelectContactFragment usuariosFragment = (SelectContactFragment) manager
								.findFragmentByTag(LIST_CONTACT_FRAGMENT);
						if (usuariosFragment == null) {
							usuariosFragment = new SelectContactFragment();

						}
						t.setCustomAnimations(android.R.anim.slide_in_left,
								android.R.anim.slide_out_right);
						t.replace(R.id.fragment_web_conteiner,
								usuariosFragment, LIST_CONTACT_FRAGMENT);

						t.commit();
					}
				});

			}
		};
		mExecutor.submit(r);

	}

	@Override
	public void onSelectThreadWeb(final long idThread) {

		Runnable r = new Runnable() {

			@Override
			public void run() {
				final ThreadWeb thread = mServiceHelper
						.getSelectThreadById(idThread);

				mHandler.post(new Runnable() {

					@Override
					public void run() {
						Log.d(TAG, "on select threadWeb: " + idThread);
						FragmentTransaction t = manager.beginTransaction();
						MessageListFragment mensaje = (MessageListFragment) manager
								.findFragmentByTag(thread.getName());
						if (mensaje == null) {
							mensaje = new MessageListFragment();
							mensaje.setThreadWeb(thread);
						}
						t.setCustomAnimations(android.R.anim.slide_in_left,
								android.R.anim.slide_out_right);
						t.replace(R.id.fragment_web_conteiner, mensaje,
								thread.getName());
						t.addToBackStack(null);
						t.commit();
					}
				});

			}
		};
		mExecutor.submit(r);
	}

	@Override
	public void backToThreads() {
		FragmentTransaction t = manager.beginTransaction();

		t.setCustomAnimations(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		t.replace(R.id.fragment_web_conteiner, mListThreadFragment,
				LIST_THREAD_FRAGMENT);
		t.addToBackStack(null);
		t.commit();
	}

	@Override
	public void backToDashboard() {
		Intent intent = new Intent(this, DashboardActivity.class);
		startActivity(intent);
	}

	public void addContact() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Agregar Contacto");
		builder.setItems(
				getResources().getStringArray(R.array.dialog_add_contact),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							Intent pick = new Intent(Intent.ACTION_PICK, Uri
									.parse("content://contacts"));
							pick.setType(Phone.CONTENT_TYPE);
							startActivityForResult(pick, PICK_REQUEST);
							dialog.dismiss();
							break;
						case 1:
							showAddContactWebFragment(new Bundle());
							break;

						default:
							dialog.dismiss();
							break;
						}
					}
				});
		AlertDialog alert = builder.create();
		alert.show();

	}

	private void showAddContactWebFragment(final Bundle bundle) {
		Runnable r = new Runnable() {

			@Override
			public void run() {
				mHandler.post(new Runnable() {

					@Override
					public void run() {

						mAddContactWebFragment = new AddContactWebFragment();
						mAddContactWebFragment.setArguments(bundle);
						FragmentTransaction t = manager.beginTransaction();
						t.setCustomAnimations(android.R.anim.slide_in_left,
								android.R.anim.slide_out_right);
						t.replace(R.id.fragment_web_conteiner,
								mAddContactWebFragment, ADD_CONTACT);
						t.commit();

					}
				});
			}

		};
		mExecutor.submit(r);
	}

	private void showThreadWebFragment() {

		FragmentTransaction t = manager.beginTransaction();
		t.setCustomAnimations(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		t.replace(R.id.fragment_web_conteiner, mListThreadFragment,
				LIST_THREAD_FRAGMENT);
		t.addToBackStack(null);
		t.commit();
	}

	@Override
	public void cancelNewContact() {
		showThreadWebFragment();
		Toast.makeText(this,
				getResources().getString(R.string.toast_cancel_new_user),
				Toast.LENGTH_SHORT).show();

	}

	@Override
	public void saveNewContact(final ContactWeb c) {
		mExecutor.submit(new Runnable() {

			@Override
			public void run() {
				mServiceHelper.saveNewContact(c);

			}
		});

		showThreadWebFragment();
		Toast.makeText(this, getResources().getString(R.string.toast_new_user),
				Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PICK_REQUEST) {
			if (resultCode == RESULT_OK) {
				Uri uri = data.getData();
				Log.d(TAG, "Contact picked=" + uri.toString());
				Bundle bundle = new Bundle();
				bundle.putString(URI_PICKED, uri.toString());
				showAddContactWebFragment(bundle);
			}
		}
	}

	@Override
	public void deleteMessage(final long idMessage) {
		Runnable r = new Runnable() {

			@Override
			public void run() {
				mServiceHelper.deleteMessage(idMessage);
			}
		};
		mExecutor.submit(r);
	}

	@Override
	public void deleteThread(final long idThread) {
		Runnable r = new Runnable() {

			@Override
			public void run() {
				mServiceHelper.deleteThread(idThread);
			}
		};
		mExecutor.submit(r);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.new_message:
			onNewMessage();
			break;
		case R.id.add_contact:
			addContact();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}
